$(function () {
  init()
  analytics.send({
    event: `${avPrefix}_open`,
    attr: {
      rid: rid,
      _p: utils.getUrlParam('_p')
    }
  })

  getBuyInfo()

  function getBuyInfo () {
    account.forceLogin = false
    account.getUserInfo((err, userInfo) => {
      if (err) {
        // 没有登录, 肯定也不会有购买了, 那就判断是否有referenceCode
        if (!rid) {
          // 没有referenceCode
          // 那就什么都不做, 显示购买界面
          console.log('没有登录, 没有购买, 没有referenceCode')
          setBuyStatus(0)
        } else {
          // 如果存在referenceCode
          // 也就是说当前页面是从其他用户分享来了
          console.log('没有登录, 没有购买, 有referenceCode')
          // 通过referenceCode那分享者的用户信息
          getReferenceByCode()
          setBuyStatus(0)
        }
      } else {
        // 已经登录, 那就要先判断自己是否已经购买
        activeShare(userInfo.shareFlag)
        checkBuying(
          () => {
            account.ajax({
              type: 'GET',
              path: `/s/bills/products/reference/${extraCampaignProduct}`,
              success: result => {
                if (result.id) {
                  // 如果已经购买过当前的9月活动
                  // 那么显示自己的购买情况
                  console.log('有登录, 但有购买过当前活动, 忽略referenceCode')
                  window.referenceInfo = result
                  window.rid = referenceInfo.referenceCode
                  activeShare(userInfo.shareFlag)
                  setBuyStatus(1)
                } else if (rid) {
                  // 如果没有购买, 但是存在referenceCode
                  // 也就是说当前页面是从其他用户分享来了
                  console.log('有登录, 没购买, 有referenceCode')
                  window.rid = rid
                  // 通过referenceCode那分享者的用户信息
                  getReferenceByCode()
                  setBuyStatus(0)
                } else {
                  // 如果没有购买, 也没有referenceCode
                  // 那就什么都不做, 显示购买界面
                  console.log('有登录, 没购买, 没有referenceCode')
                  setBuyStatus(0)
                }
              },
              error: err => console.error(err)
            })
          },
          () => {
            // 如果之前购买过任意拼读课的活动
            // 则不能再参加本次活动了
            console.log('有登录, 但之前购买过任意拼读课的活动')
            setBuyStatus(2)
            utils.alert('您已经购买过自然拼读体验课，可以点击右上角分享给朋友哦')
          }
        )
      }
    })
  }

  function checkBuying (unbuying, buying) {
    account.ajax({
      type: 'GET',
      path: `/s/my/products/1036/detail`,
      success: product1 => {
        account.ajax({
          type: 'GET',
          path: `/s/my/products/1043/detail`,
          success: product2 => {
            if (!product1.total && !product2.total) {
              unbuying()
            } else {
              buying()
            }
          },
          error: err => console.error(err)
        })
      },
      error: err => console.error(err)
    })
  }

  function getReferenceByCode () {
    account.ajax({
      auth: false,
      type: 'GET',
      path: `/s/products/${extraCampaignProduct}/reference/buying?referenceCode=${encodeURIComponent(decodeURIComponent(rid))}`,
      success: reference => {
        account.ajax({
          auth: false,
          type: 'GET',
          path: '/s/students/socials',
          data: {ids: reference.studentId},
          success: socials => {
            if (reference.status === 4) {
              console.log('任务已过期');
              utils.alert(`哦噢, ${socials && socials.length > 0 ? socials[0].nickname + '的' : '该'}解锁任务已过期，<br/>无法帮TA解锁哦`, '我也来挑战')
            } else {
              console.log('任务进行中');
              utils.alert(`${socials && socials.length > 0 ? socials[0].nickname : ''}邀请你<br/>一起解锁久趣自然拼读课`, '去看看')
            }
          },
          error: err => $.toastAlert(err.message, 2)
        })
      },
      error: err => $.toastAlert(err.message, 2)
    })
  }

  function setBuyStatus (status) {
    window.buyStatus = status
    switch (status) {
      case 1: {
        // 显示分享
        // 有登录, 有购买, 忽略referenceCode
        showCheckoutLesson(referenceInfo.referenceCount >= 2 ? 4 : 2)
        const current = Date.parse(new Date()), endAt = referenceInfo.endAt * 1000
        if (current < endAt) {
          if (referenceInfo.referenceCount === 0) {
            setCountDown(current, endAt)
            $('#buy').text('邀请2位新用户，再解锁2节课')
          } else if (referenceInfo.referenceCount === 1) {
            setCountDown(current, endAt)
            $('#buy').text('再邀请1位新用户，解锁2节课')
          } else {
            if (new Date().getTime() > 1539187199000) {
              $('#buy').hide()
              $('#stop').show()
              return
            }
            $('#buy').text('解锁完成, 分享给好友')
          }
        } else {
          if (referenceInfo.referenceCount >= 2) {
            if (new Date().getTime() > 1539187199000) {
              $('#buy').hide()
              $('#stop').show()
              return
            }
            $('#buy').text('解锁完成, 分享给好友')
          } else {
            if (new Date().getTime() > 1539187199000) {
              $('#buy').hide()
              $('#stop').show()
              return
            }
            setCountDown(current, endAt)
            $('#buy').text('分享给好友')
          }
        }
        break
      }
      case 2: {
        // 显示分享
        // 有登录, 但是购买过19.9的活动的, 忽略referenceCode
        if (new Date().getTime() > 1539187199000) {
          $('#buy').hide()
          $('#stop').show()
          return
        }
        $('#buy').text('分享给好友')
        break
      }
      case 0:
      default: {
        // 显示购买
        // 没有登录, 没有购买, 没有referenceCode
        // 没有登录, 没有购买, 有referenceCode
        // 有登录, 没有购买, 有referenceCode
        // 有登录, 没有购买, 没有referenceCode
        if (new Date().getTime() > 1539187199000) {
          $('#buy').hide()
          $('#stop').show()
          return
        }
        showCheckoutLesson(0)
        $('#buy').text('支付9元解锁2节拼读课')
      }
    }
  }

  function submitOrder (pid) {
    account.forceLogin = true
    //提交订单久趣后台
    account.getUserInfo((err, userInfo) => {
      if (err) {
        $.toastAlert(err.message)
        return
      }
      activeShare(userInfo.shareFlag)
      const payChannel = utils.isWeChat() ? 'weixin' : 'alipay'
      const openId = window.localStorage.getItem(account.openId)
      activeShare(userInfo.shareFlag)

      checkBuying(
        () => {
          account.ajax({
            type: 'GET',
            path: `/s/customers/${openId}/status`,
            success: status => {
              account.ajax({
                type: 'POST',
                path: '/s/bills',
                data: {
                  productId: pid,
                  payChannel: payChannel,
                  returnUrl: status.subscribe ? `${campUrl}${Math.ceil(Math.random() * 100)}` : `${verifyUrl}`,
                  tradeType: 'JSAPI',
                  openId: openId,
                  referenceCode: encodeURIComponent(decodeURIComponent(rid))
                },
                success: data => {
                  if (data.status !== 'error') {
                    analytics.send({
                      event: `${avPrefix}_buy`,
                      attr: {
                        rid: rid,
                        pid: pid,
                        payChannel: payChannel
                      }
                    })
                    if (utils.isWeChat()) {
                      const jsApiParameters = JSON.parse(data.jsApiParameters)
                      jsApiParameters.redirect = status.subscribe ? `${campUrl}${Math.ceil(Math.random() * 100)}` : `${verifyUrl}`

                      // 唤起微信支付
                      wxconfig.pay(data.bill_id, pid, jsApiParameters, encodeURIComponent(campUrl))
                    } else {
                      // 跳转去支付宝支付
                      window.location.href = data.url
                    }
                  } else {
                    $.toastAlert('下单失败，请重试')
                  }
                },
                error: err => {
                  if (err.code === 'product.rejected.by.bought.products') {
                    utils.alert('您已购买过自然拼读体验课')
                    getBuyInfo()
                  } else if (err.code === 'product.rejected.by.bought.products') {
                    $.toastAlert('您已经参加活动', 2)
                  } else {
                    $.toastAlert(err.message, 2)
                  }
                }
              })
            },
            error: err => $.toastAlert(err.message, 2)
          })
        },
        () => {
          setBuyStatus(2)
          utils.alert('您已经购买过自然拼读体验课，可以点击右上角分享给朋友哦')
        }
      )
    })
  }

  function showCheckoutLesson (count) {
    $('.main .progress .list .item').addClass('lock')
    for (let i = 1; i < Math.min(count, 4) + 1; i++) $(`.lesson-${i}`).removeClass('lock')
  }

  function setCountDown (current, endAt) {
    let countDown = setInterval(() => {
      if (current >= endAt) {
        $('.notice').text('未能解锁成功, 上完2节课还可以再次解锁哦~')
        $('.notice').show()
        clearInterval(countDown)
      } else if (current < endAt) {
        const timeDiff = endAt - current
        const day = Math.floor(timeDiff / 1000 / 60 / 60 / 24)
        const hour = Math.floor(timeDiff / 1000 / 60 / 60 % 24)
        const min = Math.floor(timeDiff / 1000 / 60 % 60)

        $('.notice .title').text('剩余时间：')
        $('.notice .day-1').text(Math.floor(day / 10))
        $('.notice .day-2').text(Math.floor(day % 10))
        $('.notice .hour-1').text(Math.floor(hour / 10))
        $('.notice .hour-2').text(Math.floor(hour % 10))
        $('.notice .min-1').text(Math.floor(min / 10))
        $('.notice .min-2').text(Math.floor(min % 10))
        $('.notice').show()
      }
    }, 1000)
  }

  // 内容介绍等级切换按钮
  $('.level-buttons > div').off('click').on('click', e => {
    $('.level').attr('class', 'level ' + e.target.className)
  })

  // 点击购买按钮
  $('#buy').off('click').on('click', () => {
    if (buyStatus) $('.share-mask').fadeIn()
    else submitOrder($('#buy').attr('data-pid'))
  })

  // 解锁课程点击按钮
  $('.progress > .list > .item').off('click').on('click', () => {
    if (!buyStatus) submitOrder($('#buy').attr('data-pid'))
  })

  // 关闭分享提示
  $('.share-mask').click(() => {
    $('.share-mask').fadeOut()
  })

  // 切换账号
  $('#switch-account').off('click').on('click', () => {
    $('.account-mask').fadeOut()
    account.forceLogin = true
    account.checkLoginStatus(() => {
      account._showLogin(() => {
        console.log('登录成功, 刷新数据')
        getBuyInfo()
      }, true)
    })
  })
})

function init () {
  window.campaign = 'phonics'
  window.campUrl = `${window.location.protocol}//${window.location.host}/wx/${window.campaign}`
  window.verifyUrl = `${campUrl}/verifypayment?type=1`
  window.avPrefix = 'p004'
  window.analytics = AV.analytics({
    appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
    appKey: 'jqyWxLyobpsmdwsJddJlDheb',
    channel: utils.isWeChat() ? 'weixin' : ''
  })
  window.wxconfig = new WxConfig(wechatConfig, 'phonics')
  window.account = new Account()
  window.rid = getRid()
  window.localStorage.setItem('_rid', rid)
  console.log(`rid=${rid}`)
  window.shareFlag = ''
  window.shareMsg = shareFlag => {
    return {
      title: '限时！久趣自然拼读，9元解锁2节课！',
      desc: '北美外教在线教学，让孩子轻松认读新单词！',
      link: `${campUrl}${Math.ceil(Math.random() * 100)}?_c=${window.campaign}&_r=${shareFlag}&_rid=${rid}&_p=cshre`,
      imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png',
      success: target => {
        analytics.send({
          event: `${avPrefix}_share_success`,
          attr: {
            target: target
          }
        })
      }
    }
  }
  window.activeShare = shareFlag => {
    if (utils.isWeChat()) window.shareFlag = shareFlag || ''
    wxconfig.activeShare(shareFlag, '', shareMsg(shareFlag))
  }
  if (!utils.getUrlParam('_c')) {
    const QKidsChannel = JSON.parse(window.localStorage.getItem('QKidsChannel'))
    if (!(QKidsChannel && QKidsChannel.expires > new Date().getTime() / 1000)) {
      window.localStorage.setItem('QKidsChannel', JSON.stringify({
        rawData: `${campaign}_share`,
        expires: new Date().getTime() / 1000 + 24 * 3600
      }))
    }
  }
}

function getRid () {
  if (utils.getUrlParam('_rid')) return utils.getUrlParam('_rid')
  else if (window.localStorage.getItem('_rid')) return window.localStorage.getItem('_rid')
  else return ''
}